import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Space,
  Button,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Form,
  Typography,
  Avatar,
  Tooltip,
  Empty,
  Spin,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  PushpinOutlined,
  SendOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionFilter,
  DiscussionReply,
} from "../../common/types/discussion";
import { useUser } from "../../../contexts/UserContext";
import discussionService from "../../../services/discussion";
import NewDiscussion from "./components/NewDiscussion";
import DiscussionDetail from "./components/DiscussionDetail";

const { Search } = Input;
const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ReplyForm = styled(Form)`
  margin-top: 16px;
  .ant-form-item:last-child {
    margin-bottom: 0;
  }
`;

const StudentDiscussion: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [isNewDiscussionVisible, setIsNewDiscussionVisible] = useState(false);
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [replyForm] = Form.useForm();

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      const { discussions: data } = await discussionService.getDiscussions(
        "all",
        filter
      );
      setDiscussions(data);
    } catch (error) {
      message.error("加载讨论列表失败");
      console.error("加载讨论列表失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleTagClick = (tag: string) => {
    setFilter({
      ...filter,
      tags: filter.tags?.includes(tag)
        ? filter.tags.filter((t) => t !== tag)
        : [...(filter.tags || []), tag],
    });
  };

  const handleNewDiscussion = () => {
    if (!user) {
      message.warning("请先登录");
      return;
    }
    setIsNewDiscussionVisible(true);
  };

  const handleNewDiscussionSubmit = async (values: {
    title: string;
    content: string;
    tags: string[];
  }) => {
    if (!user) return;

    try {
      await discussionService.createDiscussion("all", {
        ...values,
        author: {
          id: user.id,
          name: user.name,
          role: user.role,
        },
      });
      message.success("发布成功！");
      setIsNewDiscussionVisible(false);
      loadDiscussions();
    } catch (error) {
      message.error("发布失败，请重试");
      console.error("发布讨论失败:", error);
    }
  };

  const handleLike = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      await discussionService.likeDiscussion(discussionId, user.id);
      loadDiscussions();
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  const handleReply = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      const values = await replyForm.validateFields();
      await discussionService.addReply(discussionId, {
        content: values.content,
        author: {
          id: user.id,
          name: user.name,
          role: user.role,
        },
        likes: 0,
      });
      replyForm.resetFields();
      message.success("回复成功！");
      loadDiscussions();
    } catch (error) {
      if (error instanceof Error) {
        message.error("回复失败，请重试");
        console.error("回复失败:", error);
      }
    }
  };

  return (
    <div style={{ padding: "24px" }}>
      <StyledCard
        title={
          <Space>
            <Title level={4} style={{ margin: 0 }}>
              课程讨论区
            </Title>
          </Space>
        }
        extra={
          <Space>
            <Search
              placeholder="搜索讨论..."
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
            <Select
              value={filter.sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
              options={[
                { label: "最新", value: "latest" },
                { label: "最热", value: "popular" },
                { label: "最多回复", value: "mostReplies" },
              ]}
            />
            <Button type="primary" onClick={handleNewDiscussion}>
              发起讨论
            </Button>
          </Space>
        }
      >
        {loading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin />
          </div>
        ) : discussions.length === 0 ? (
          <Empty description="暂无讨论" />
        ) : (
          <List<DiscussionPost>
            itemLayout="vertical"
            dataSource={discussions}
            renderItem={(item) => (
              <List.Item
                key={item.id}
                actions={[
                  <Tooltip title="浏览数">
                    <Space>
                      <EyeOutlined />
                      {item.views}
                    </Space>
                  </Tooltip>,
                  <Tooltip title={user ? "点赞" : "登录后即可点赞"}>
                    <Button
                      type="text"
                      icon={<LikeOutlined />}
                      onClick={() => handleLike(item.id)}
                      disabled={!user}
                    >
                      {item.likes}
                    </Button>
                  </Tooltip>,
                  <Tooltip title="回复数">
                    <Space>
                      <MessageOutlined />
                      {item.replies.length}
                    </Space>
                  </Tooltip>,
                ]}
                extra={
                  item.aiResponse && (
                    <Tag icon={<RobotOutlined />} color="purple">
                      AI已回复
                    </Tag>
                  )
                }
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<UserOutlined />} />}
                  title={
                    <Space>
                      {item.isPinned && (
                        <Tooltip title="已置顶">
                          <PushpinOutlined style={{ color: "#1890ff" }} />
                        </Tooltip>
                      )}
                      <a
                        href="#"
                        onClick={(e) => {
                          e.preventDefault();
                          setSelectedDiscussion(item.id);
                        }}
                      >
                        {item.title}
                      </a>
                    </Space>
                  }
                  description={
                    <Space>
                      <Text>{item.author.name}</Text>
                      <Tag
                        color={
                          item.author.role === "teacher" ? "blue" : undefined
                        }
                      >
                        {item.author.role === "teacher" ? "教师" : "学生"}
                      </Tag>
                      <Text type="secondary">发布于 {item.createTime}</Text>
                      {item.tags.map((tag) => (
                        <Tag
                          key={tag}
                          color={
                            filter.tags?.includes(tag) ? "blue" : undefined
                          }
                          style={{ cursor: "pointer" }}
                          onClick={() => handleTagClick(tag)}
                        >
                          {tag}
                        </Tag>
                      ))}
                    </Space>
                  }
                />
                <Paragraph
                  ellipsis={{ rows: 2, expandable: true, symbol: "展开" }}
                >
                  {item.content}
                </Paragraph>
                {user && (
                  <ReplyForm form={replyForm}>
                    <Form.Item
                      name="content"
                      rules={[{ required: true, message: "请输入回复内容" }]}
                    >
                      <TextArea
                        placeholder="写下你的回复..."
                        autoSize={{ minRows: 2, maxRows: 6 }}
                        maxLength={500}
                        showCount
                      />
                    </Form.Item>
                    <Form.Item style={{ textAlign: "right", marginBottom: 0 }}>
                      <Button
                        type="primary"
                        icon={<SendOutlined />}
                        onClick={() => handleReply(item.id)}
                      >
                        发表回复
                      </Button>
                    </Form.Item>
                  </ReplyForm>
                )}
              </List.Item>
            )}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条讨论`,
            }}
          />
        )}
      </StyledCard>

      <NewDiscussion
        visible={isNewDiscussionVisible}
        onCancel={() => setIsNewDiscussionVisible(false)}
        onSubmit={handleNewDiscussionSubmit}
      />

      {selectedDiscussion && (
        <DiscussionDetail
          discussionId={selectedDiscussion}
          onClose={() => setSelectedDiscussion(undefined)}
        />
      )}
    </div>
  );
};

export default StudentDiscussion;
